package com.ks.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {
    private static String dirverName;
    private static String url;
    private static String username;
    private static String password;

    // 利用静�?块i，在类加载的时�?就被执行
    static {
        try {
            // 用流读入properties配置文件
            InputStream inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            // 从输入字节流读取属�?列表（键和元素对�?
            properties.load(inputStream);
            // 用此属�?列表中指定的键搜索属性，获取驱动，url，username，password
            dirverName = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            // 加载驱动
            Class.forName(dirverName);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    // 获取数据库连�?
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     *
     * @param cs
     * @param stmt
     * @param rs
     * @param conn
     */
    public static void close(CallableStatement cs, Statement stmt, ResultSet rs, Connection conn) {
        try {
            if (cs != null) {
                cs.close();
            }
        } catch (SQLException ex) {
            // Logger.getLogger(PrimaryConnectionUtil.class.getName()).log(Level.SEVERE,
            // null, ex);
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != rs) {
                        rs.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != conn) {
                            conn.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}